<template>
  <div class="accessList">
    <!-- table -->
      <accessTable
        v-if="!isShowAccessCode"
        :isAdd="limitArr.indexOf('access_list_insert') > -1"
        @addFun="addFun"
        @search="queryTableList"
        @sizeChange="sizeChange"
        @currentChangeFun="currentChangeFun"
        :quickSearchForm="quickSearchForm"
        :tableHeader="tableHeader"
        :tablePages="tablePages"
        :tableData="tableData">
      </accessTable>
    <!-- 抽屉 -->
      <drawer
        direction="rtl"
        :title="drawer.title"
        :drawer="drawer.isShow"
        @save="confirmFun"
        @cancelFun="cancelFun"
        @closeDraw="cancelFun">
        <template slot="column">
          <accessAddOrEdit ref="accessInfo" :cssTemData="cssTemData"></accessAddOrEdit>
        </template>
      </drawer>
      <!-- 接入代码 -->
    <accessCode v-if="isShowAccessCode" :codeInfo="codeInfo" @codeBack="codeBack"></accessCode>
  </div>

</template>
<script lang='ts'>
import { Component, Vue, Ref } from 'vue-property-decorator'
import accessTable from '../base/accessTable.vue'
import drawer from '@/common/views/drawer/index.vue'
import accessAddOrEdit from '@/views/config/webchat/channel/pcAndWap/accessAddOrEdit.vue'
import { CommonModule } from '@/store/modules/common'
import { channelConfigMoudle } from '@/store/modules/config/channel/index'
import { deepClone } from '@/utils/common'
import accessCode from '@/views/config/webchat/channel/pcAndWap/accessCode.vue'
import { checkPermission } from '@/utils/directive'
// eslint-disable-next-line no-unused-vars
import { Form as ElForm } from 'element-ui'
interface InterStatus {
  [x: string]: any
  status: 'enable' | 'disable'
}
interface TableItem {
  accessId: string,
  status?: string,
  _id?: string
}
@Component({
  name: 'accessList',
  components: {
    accessTable,
    drawer,
    accessAddOrEdit,
    accessCode
  }
})
export default class AccessList extends Vue {
  @Ref() private readonly accessInfo !: accessAddOrEdit
  private $message: any
  private $confirm: any
  private $store: any
  private $deleteCache: any
  private $getCache: any

  private satisfactionId = ''

  private limitArr: any = [] // 权限

  private quickSearchForm: any = { // 快捷检索数据（网站名称）
    form: {
      name: '' // 网站名称
    },
    advSearchOptions: [
      { label: '网站名称', inputType: 'input', placeholder: '请输入网站名称', name: 'name', clearable: true }
    ]
  }

  private codeInfo = {} // 接入代码信息

  private webchatUrl = '' // 访客端访问地址

  private statusMap = { // 渠道状态
    open: { name: '启用', iconClass: 'green-color V7_iconV7tubiao_dian' },
    close: { name: '停用', iconClass: 'red-color V7_iconV7tubiao_dian' }
  }

  private drawer = { // 详情抽屉
    title: '添加渠道', // 标题
    isShow: false // 是否展示
  }

  private isShowAccessCode = false // 是否展示接入代码

  private cssTemData = [] // css样式模板

  private tableHeader: any = [ // table表头
    { label: '接入号', prop: 'accessId', width: 150 },
    { label: '网站名称', prop: 'name', isSort: true },
    { label: '状态', prop: 'status', isDictionary: true, dictionary: this.statusMap, showStatusIcon: true, isSort: true, width: 70 },
    { label: '流程', prop: 'processName' },
    { label: '样式', prop: 'cssTmpName' },
    { label: '创建人', prop: 'createName' },
    { label: '最后更新时间', prop: 'createTime', isSort: true, width: 145 }
  ]

  private tablePages = { // 翻页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private tableData = [] // table数据

  private confirmFun () { // 保存事件
    this.$nextTick(() => {
      const formRef = this.accessInfo.$refs.accessForm as ElForm
      formRef.validate(valide => {
        if (valide) {
          let sendUrl = '/im-web/action/config/channel/save'
          const sendData = deepClone(this.accessInfo.accessForm)
          const inviteParamSettings = deepClone(this.accessInfo.invitationForm)
          let successMsg = '添加渠道成功'
          if (sendData._id) {
            sendUrl = '/im-web/action/config/channel/update'
            successMsg = '编辑渠道成功'
          } else {
            sendData.satisfactionId = this.satisfactionId
          }
          const actionData = { url: sendUrl, method: 'POST', data: { ...sendData, inviteParamSettings } }
          channelConfigMoudle.channelCommonAction(actionData).then(res => {
            if (res) {
              this.drawer.isShow = false
              this.$message.success(successMsg)
              this.queryTableList(sendData._id === '' ? 'add' : null)
              if (!sendData._id) {
                (this as any).$addOneCache('channelList', res.data, true) // 更新渠道缓存
              } else {
                (this as any).$updateCache('channelList', res.data, '_id', true) // 更新渠道缓存
              }
              this.accessInfo.setAccessData()
            }
          })
        }
      })
    })
  }

  private handleState (obj: InterStatus) { // 渠道状态切换
    const statusMap = { open: 'open', close: 'close' }
    const status = statusMap[obj.status]
    const statusName = status === 'open' ? '停用' : '启用'
    const sendUrl = '/im-web/action/config/channel/updateStatus'
    const sendData = { url: sendUrl, data: { _id: obj._id, status: status === 'open' ? 'close' : 'open' }, method: 'POST' }
    this.$confirm(`确定要${statusName}该渠道吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      channelConfigMoudle.channelCommonAction(sendData).then(res => {
        if (res) {
          this.$message.success('变更渠道状态成功')
          this.queryTableList()
        }
      })
    })
  }

  private queryTableList (addSuccess?: any) { // 查询table数据
    if (addSuccess) { // 新增回到第一页
      this.tablePages.current = 1
    }
    const sendData = { page: this.tablePages.current, limit: this.tablePages.pageSize, query: { ...this.quickSearchForm.form } }
    const actionData = { url: '/im-web/action/config/channel/list', method: 'POST', data: { ...sendData } }
    channelConfigMoudle.channelCommonAction(actionData).then(res => {
      if (res.data.list) {
        const list = res.data.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.tablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.tablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.tablePages.current = page
            this.queryTableList()
            return false
          }
        }
        if (list.length > 0) {
          list.forEach((item: any) => {
            const cssTemItem: any = deepClone(CommonModule.publicCache.cssListObj[item.cssTmpId])
            item.cssTmpName = (cssTemItem && cssTemItem.name) || '--' // 样式名称
            const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.createUser]
            item.createName = agentObj ? agentObj.name : '--' // 创建人
            const processObj = deepClone(CommonModule.publicCache.processListObj)[item.processId]
            item.processName = processObj ? processObj.name : '--' // 流程名称
          })
        }
        this.tableData = res.data.list
        this.webchatUrl = res.data.webchatUrl
        this.tablePages.total = res.data.count || 0
      }
    })
  }

  private addFun () { // 点击新增事件
    this.drawer.isShow = true
  }

  private cancelFun () { // 抽屉取消事件
    this.drawer.isShow = false
    this.accessInfo.setAccessData() // 取消时需要清空抽屉表单内容
  }

  private sizeChange (size: number) { // 更改table显示页数
    this.tablePages.pageSize = size
    this.queryTableList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.tablePages.current = page
    this.queryTableList()
  }

  private editFun (obj: any) { // 编辑渠道
    this.drawer.isShow = true
    this.drawer.title = '编辑渠道'
    this.$nextTick(() => {
      obj.satisfactionId = this.satisfactionId
      this.accessInfo.setAccessData(obj)
    })
  }

  private testFun (row: TableItem) { // 测试btn事件
    window.open(this.webchatUrl + 'demo.html?accessId=' + row.accessId)
  }

  private accessFun (row: TableItem) { // 接入代码事件
    this.codeInfo = { url: this.webchatUrl, accessId: row.accessId }
    this.isShowAccessCode = true
  }

  private codeBack () { // 接入代码返回事件
    this.isShowAccessCode = false
  }

  private delFun (row: TableItem) { // 删除渠道
    if (row.status === 'open') { // 只有停用的渠道才可以删除
      this.$message.error('请先停用该渠道再删除')
      return
    }
    const sendData = { url: '/im-web/action/config/channel/delete', method: 'POST', data: { _id: row._id } }
    this.$confirm('确定要删除该渠道吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      channelConfigMoudle.channelCommonAction(sendData).then(res => {
        if (res) {
          this.$message.success('删除渠道成功')
          this.$deleteCache('channelList', '_id', row._id, true)
          this.queryTableList()
        }
      })
    })
  }

  private mounted () {
    let handlers: any = []
    this.limitArr = this.$store.state.common.session.user.functions // 权限处理
    if (checkPermission(null, { value: ['access_list_edit'] })) { // 编辑权限
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) })
    }
    if (checkPermission(null, { value: ['access_list_test'] })) { // 测试代码权限
      handlers = [...handlers,
        ...[
          { name: '测试', handleFn: (scope: any) => this.testFun(scope.row) }
        ]
      ]
    }
    if (checkPermission(null, { value: ['access_list_join'] })) { // 接入代码权限
      handlers = [...handlers,
        ...[
          { name: '接入代码', handleFn: (scope: any) => this.accessFun(scope.row) }
        ]
      ]
    }
    if (checkPermission(null, { value: ['access_list_enableOrDisable'] })) { // 停用启用权限
      handlers = [...handlers,
        ...[
          { name: '停用', className: 'danger', field: 'status', status: 'open', handleFn: (scope: any) => this.handleState(scope.row) },
          { name: '启用', field: 'status', status: 'close', handleFn: (scope: any) => this.handleState(scope.row) }
        ]
      ]
    }
    if (checkPermission(null, { value: ['access_list_delete'] })) { // 删除权限
      handlers = [...handlers,
        ...[
          { name: '删除', className: 'danger', isShowSystemDelBtn: true, handleFn: (scope: any) => this.delFun(scope.row) }
        ]
      ]
    }
    this.tableHeader.push({ label: '操作', width: 220, handlers })
    const channelCache = this.$getCache('/im-center/action/webchat/channelCache', ['cssList', 'channelList'], true) // 获取渠道列表，样式缓存
    const processCache = this.$getCache('/im-center/action/config/processConfig/processCache', ['processList'], true) // 获取流程缓存
    Promise.all([processCache, channelCache]).then(res => {
      this.cssTemData = this.$store.state.common.publicCache.cssList || []
      this.queryTableList()
    })
    const actionData = { url: '/im-center/action/config/satisfaction/list', method: 'POST', data: {} }
    channelConfigMoudle.channelCommonAction(actionData).then(res => {
      if (res && res.success && res.data && res.data.list) {
        const currentObj = res.data.list.filter(item => {
          return item.isDefault
        })
        this.satisfactionId = currentObj[0]._id
      }
    })
  }
}
</script>
<style lang="stylus">
 .accessList
  height 100%
</style>
